package com.jungle.client;

import com.google.gson.reflect.TypeToken;
import com.jungle.bfi.domain.vo.DataCategoryVo;
import com.jungle.client.channel.HttpClient;
import com.jungle.client.utils.TableViewUtil;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.Consumer;

@Slf4j
public class DataCategoryController implements Initializable {
    @FXML
    Button addButton;
    @FXML
    Button editButton;
    @FXML
    Button deleteButton;
    @FXML
    Button moveUpButton;
    @FXML
    Button moveDownButton;

    @FXML
    TableView<DataCategoryVo> tableView;

    @FXML
    TableColumn<DataCategoryVo, String> nameColumn;
    @FXML
    TableColumn<DataCategoryVo, String> codeColumn;

    public void initialize(URL location, ResourceBundle resources) {
        log.info("init DataSetController, location:{}", location);
        initialize();
    }

    private void initialize() {
        //加载数据
        TypeToken<List<DataCategoryVo>> typeToken = new TypeToken<>() {
        };
        HttpClient.getInstance().post("/dataCategory/list", "{}").callback(typeToken,
                list -> {
                    if (list != null && !list.isEmpty()) {
                        tableView.getItems().clear();
                        tableView.getItems().addAll(list);
                    }
                }
        );
        tableView.getSelectionModel().selectedIndexProperty().addListener((observable, oldIndex, selectedIndex) -> {
            if (selectedIndex == null || selectedIndex.intValue() == -1) {
                editButton.setDisable(true);
                deleteButton.setDisable(true);
                moveUpButton.setDisable(true);
                moveDownButton.setDisable(true);
            } else {
                editButton.setDisable(false);
                deleteButton.setDisable(false);
                // 判断是否是为第一行，如果是则禁用上移按钮
                int index = selectedIndex.intValue();
                log.debug("selectedIndex:{},size():{}", index, tableView.getItems().size());
                moveUpButton.setDisable(index == 0);
                // 判断是否是最后一行，如果是则禁用下移按钮
                moveDownButton.setDisable(index == tableView.getItems().size() - 1);
            }
        });
    }

    public void doAdd(ActionEvent actionEvent) {
        // 添加一行数据
        log.info("doAdd:{}", actionEvent);
        addData();
    }

    private void addData() {
        try {
            DataCategoryDialogController.showAddDialog(new DataCategoryVo(), storeData(
                            dataCategoryPo -> {
                                tableView.getItems().add(dataCategoryPo);
                                tableView.getSelectionModel().select(dataCategoryPo);
                            }
                    )
            );
        } catch (Exception e) {
            log.error("doAdd error:", e);
        }
    }

    public void doEdit(ActionEvent actionEvent) {
        log.info("doEdit:{}", actionEvent);
        int index = tableView.getSelectionModel().getSelectedIndex();
        editData(index);
    }

    private void editData(int index) {
        try {
            DataCategoryVo selectedItem = tableView.getItems().get(index);
            DataCategoryDialogController.showEditDialog(selectedItem, storeData(dataCategoryPo -> tableView.getItems().set(index, dataCategoryPo)));
        } catch (Exception e) {
            log.error("doEdit error:", e);
        }
    }

    private static Consumer<DataCategoryVo> storeData(final Consumer<DataCategoryVo> consumer) {
        return vo -> HttpClient.getInstance().post("/dataCategory/store", vo).callback(DataCategoryVo.class, consumer);
    }

    public void doDelete(ActionEvent actionEvent) {
        log.info("doDelete:{}", actionEvent);
        DataCategoryVo selectedItem = tableView.getSelectionModel().getSelectedItem();
        if (selectedItem == null) {
            return;
        }
        Alert alert = new Alert(Alert.AlertType.WARNING, "确定删除吗？");
        alert.showAndWait().ifPresent(result -> {
            if (result == ButtonType.OK) {
                log.info("删除选中的行");
                String itemId = selectedItem.getId();
                if (itemId == null) {
                    tableView.getItems().remove(selectedItem);
                } else {
                    HttpClient.getInstance().post("/dataCategory/delete", itemId).callback(Void.class,
                            resp -> {
                                log.info("resp:{}", resp);
                                tableView.getItems().remove(selectedItem);
                            }
                    );
                }
            }
        });
    }

    public void doMoveUp(ActionEvent actionEvent) {
        // 上移选中的行
        log.info("doMoveUp:{}", actionEvent);
// 获取选中的行
        int selectedIndex = tableView.getSelectionModel().getSelectedIndex();
        if (selectedIndex > 0) {
            // 交换选中行和上一行的数据
            DataCategoryVo selectedPerson = tableView.getItems().get(selectedIndex);
            DataCategoryVo previousPerson = tableView.getItems().get(selectedIndex - 1);
            tableView.getItems().set(selectedIndex - 1, selectedPerson);
            tableView.getItems().set(selectedIndex, previousPerson);

            // 重新选中移动后的行
            tableView.getSelectionModel().select(selectedIndex - 1);
        }
    }

    public void doMoveDown(ActionEvent actionEvent) {
        // 下移选中的行
        log.info("doMoveDown:{}", actionEvent);
        // 获取选中的行
        int selectedIndex = tableView.getSelectionModel().getSelectedIndex();
        if (selectedIndex < tableView.getItems().size() - 1 && selectedIndex >= 0) {
            // 交换选中行和下一行的数据
            DataCategoryVo selectedPerson = tableView.getItems().get(selectedIndex);
            DataCategoryVo nextPerson = tableView.getItems().get(selectedIndex + 1);
            tableView.getItems().set(selectedIndex + 1, selectedPerson);
            tableView.getItems().set(selectedIndex, nextPerson);

            // 重新选中移动后的行
            tableView.getSelectionModel().select(selectedIndex + 1);
        }
    }

    public void doRefresh(ActionEvent actionEvent) {
        log.info("doRefresh:{}", actionEvent);
        initialize();
    }

    public void onMouseClicked(MouseEvent mouseEvent) {
        if (mouseEvent.getClickCount() == 2) {
            log.info("onMouseClicked:{}", mouseEvent);
            TableViewUtil.traceTableRow(mouseEvent, tableRow -> {
                if (tableRow.isEmpty()) {
                    addData();
                } else {
                    editData(tableRow.getIndex());
                }
            });
        }
    }

}
